package org.eztouch.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eztouch.common.util.DataUtil;
import org.eztouch.service.SysMenuClinet;
import org.eztouch.service.SysUserClinet;
import org.eztouch.sys.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	@Value("${captchaEbabled}")
	private String captchaEbabled;
	@Autowired
	private SysMenuClinet sysMenuService;
	@Autowired
	private SysUserClinet sysUserService;
//	@Autowired
//    private DreamCaptcha dreamCaptcha;
	
	 /**
     * 图形验证码
     */
	@RequestMapping("/captcha.jpg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
    	//dreamCaptcha.generate(request, response);
    }
    
	@RequestMapping("/loginPage")
	public String loginPage(Model model){
		log.debug("是否启用验证码："+captchaEbabled);
		model.addAttribute("captchaEbabled", captchaEbabled);
		return "login";
	}
	
	@RequestMapping("/login")
	public String login(String username,String password,String captchaCode,Model model,HttpServletRequest request, HttpServletResponse response){
		String error = "";
		if(DataUtil.isEmpty(username) || DataUtil.isEmpty(password)){
			error = "用户名或者密码不能为空！";
			log.error(error);
			model.addAttribute("captchaEbabled", captchaEbabled);
			model.addAttribute("message", error);
			return "login";
		}
		
//		if("true".equals(captchaEbabled) && !dreamCaptcha.validate(request, response, captchaCode)){//启用验证码，则需校验
//			error = "验证码不正确！";
//			model.addAttribute("captchaEbabled", captchaEbabled);
//			model.addAttribute("message", error);
//			return "login";
//		}
		
		SysUser sysUser = sysUserService.selectByUserName(username);
		if(DataUtil.isEmpty(sysUser) || !sysUser.getUserPassword().equals(password)){
			error = "用户名或者密码错误！";
			log.error(error);
			model.addAttribute("captchaEbabled", captchaEbabled);
			model.addAttribute("message", error);
			return "login";
		}
		
		//获取用户角色
		String roleIds = "";
		//获取用户菜单
		String MenuTree = buildPermissionTree(roleIds);
		model.addAttribute("tree", MenuTree);
		
		return "index";
	}
	
	/**
	 * 根据操作员拥有的角色ID,构建管理后台的树形权限功能菜单
	 */
	@SuppressWarnings("rawtypes")
	public String buildPermissionTree(String roleIds) {
		List treeData = null;
		try {
			treeData = sysMenuService.listByRoleIds(roleIds);
			if (DataUtil.isNotEmpty(treeData)) {
				StringBuffer strJson = new StringBuffer();
				buildAdminPermissionTree("0", strJson, treeData);
				return strJson.toString();
			}
			log.error("用户没有分配菜单权限");
		} catch (Exception e) {
			log.error("根据角色查询菜单出现错误", e);
		}
		return "您还没有分配权限";
	}

	/**
	 * 构建管理后台的树形权限功能菜单
	 * 
	 * @param pId
	 * @param treeBuf
	 * @param menuList
	 */
	@SuppressWarnings("rawtypes")
	private void buildAdminPermissionTree(String pId, StringBuffer treeBuf, List menuList) {

		List<Map> listMap = getSonMenuListByPid(pId, menuList);
		for (Map map : listMap) {
			String id = map.get("id").toString();// id
			String name = map.get("name").toString();// 名称
			String isLeaf = map.get("isLeaf").toString();// 是否叶子
			String level = map.get("level").toString();// 菜单层级（1、2、3、4）
			String url = map.get("url").toString(); // ACTION访问地址
			String navTabId = "";
			if (!DataUtil.isEmpty(map.get("targetName"))) {
				navTabId = map.get("targetName").toString(); // 用于刷新查询页面
			}

			if ("1".equals(level)) {
				treeBuf.append("<div class='accordionHeader'>");
				treeBuf.append("<h2> <span>Folder</span> " + name + "</h2>");
				treeBuf.append("</div>");
				treeBuf.append("<div class='accordionContent'>");
			}

			if ("YES".equals(isLeaf)) {
				treeBuf.append("<li><a href='" + url + "' target='navTab' rel='" + navTabId + "'>" + name + "</a></li>");
			} else {

				if ("1".equals(level)) {
					treeBuf.append("<ul class='tree treeFolder'>");
				} else {
					treeBuf.append("<li><a>" + name + "</a>");
					treeBuf.append("<ul>");
				}

				buildAdminPermissionTree(id, treeBuf, menuList);

				if ("1".equals(level)) {
					treeBuf.append("</ul>");
				} else {
					treeBuf.append("</ul></li>");
				}

			}

			if ("1".equals(level)) {
				treeBuf.append("</div>");
			}
		}

	}

	/**
	 * 根据(pId)获取(menuList)中的所有子菜单集合.
	 * 
	 * @param pId
	 *            父菜单ID.
	 * @param menuList
	 *            菜单集合.
	 * @return sonMenuList.
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List<Map> getSonMenuListByPid(String pId, List menuList) {
		List sonMenuList = new ArrayList<Object>();
		for (Object menu : menuList) {
			Map map = (Map) menu;
			if (map != null) {
				String parentId = map.get("parentId").toString();// 父id
				if (parentId.equals(pId)) {
					sonMenuList.add(map);
				}
			}
		}
		return sonMenuList;
	}
}
